package com.yzf.demo.demo.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by 于占峰 on 2020/4/5/005.
 */
public class FileDemo {
    /**
     * 根据控制台输入的路径进行目录遍历
     *
     * @param args
     */
    public static void main(String[] args) {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(isr);
        try {
            String path = bufferedReader.readLine();//读取输入的路径
            File file = new File(path);
            if (file.isDirectory() && file.exists()) {//如果是文件夹 并且存在则遍历
                fileListIterator(file);//遍历file
            } else {
                System.out.println("文件路径错误!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private static void fileListIterator(File file) {
        File[] files = file.listFiles();//拿到所有子文件目录
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //如果是文件则输出文件名
                    System.out.println(files[i].getName());
                } else {
                    //如果是目录继续遍历
                    fileListIterator(files[i]);
                }
            }
        }
    }

}
